/**
 * 文章新增|编辑弹出框
 * 
 */

import React, { Component, PropTypes } from 'react';
import {Row, Col, Form, Input, InputNumber, TreeSelect, Button, Icon, Modal, Radio} from 'antd'
import { List, Map, is} from 'immutable'
import { Link } from 'react-router'
//import QMUeditor from 'components/qm-editor';
import { QMUeditor } from 'qm-bus'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

const noop = ()=>{}
class ArticleDialog extends Component {
    static propTypes = {
        onOk:PropTypes.func,
        onCancel:PropTypes.func,
        article:PropTypes.object
    };

    static defaultProps = {
        onOk:noop,
        onCancel:noop,
        article:Map({}),
        visible:false,
        title:'新增文章',
        options:List.of(),//栏目列表数据
        activeSectionId:''//当前默认选中的栏目编号
    }

    constructor(props){
        super(props);
        //编辑器内容
        this.editor = null;
        this.state = {
            content:''
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        if(this.props.visible === nextProps.visible && !nextProps.visible){
            return false;
        }
        return true;
    }
    
    componentWillReceiveProps(nextProps) {
        if(nextProps.visible && nextProps.article && nextProps.article.get('id')){
            let content = nextProps.article.get('content');
            //显示并保存已有内容
            this.setState({
                content:content
            })
            //已经有editor，需要重新设置内容，props无效果
            if(this.editor){
                this.editor.setContent(content);
            }
        }else if(!nextProps.visible){
            //关闭弹出窗
            this.setState({
                content:''
            })
            if(this.editor){
                this.editor.setContent('');
            }
            this.props.form.resetFields();
        }
    }
    
    componentWillUnmount() {
        this.handleChange('');
    }
    
    render() {
        const { title, visible, form, options, activeSectionId, article } = this.props; 
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 18 },
        };

        const inputStyle = {width:220,marginRight:5};

        let hiddenId = null;
        if(article.get('id')){
            //编辑栏目，就要创造一个hidden的input
            hiddenId = form.getFieldDecorator('id',{
                initialValue:article.get('id')
            })(
                <Input type="hidden" />
            )
        }
        //文章标题
        const nameField = form.getFieldDecorator('title',{
            initialValue:article.get('title') || '',
            rules:[
                {required:true,message:"请输入文章标题"},
                {type:"string",min:1,max:25,message:"文章标题限制1-25字"}
            ]
        })(
            <Input placeholder="" style={inputStyle} />
        )

        var defaultSection = '';
        if(article.get('id')){
            defaultSection = article.get('columnId');
        }else if(options.count() > 0){
            if(activeSectionId){
                /**
                 * 1.栏目页面，新增文章，包含activeSectionId
                 * 2.文章页面
                 *      新增文章没有此id
                 *      编辑文章走上面的条件
                 */
               // defaultSection = options.find(item=>item.get('key') === activeSectionId) ? activeSectionId : options.getIn([0,'value']);
               defaultSection = activeSectionId;
            }else{
                defaultSection = options.getIn([0,'value'])
            }
        }
        //文章栏目
        const sectionField = form.getFieldDecorator('columnId',{
            initialValue:defaultSection.toString()
        })(
            <TreeSelect
                treeData={options.toJS()}
                notFoundContent="未发现相关栏目"
                size="default" 
                showSearch
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="选择文章栏目"
                allowClear
                treeDefaultExpandAll
                style={inputStyle}
             />
        )

        const authorField = form.getFieldDecorator('author',{
            initialValue:article.get('author') || '',
            rules:[
                { type:"string",min:1,max:25,message:"作者名称限制：1-25个字"}
            ]
        })(
            <Input placeholder="" style={inputStyle} />
        )
        //是否专题
        const uniqueField = form.getFieldDecorator('special',{
            initialValue: article.get("special") || 'N'
        })(
            <RadioGroup>
                <Radio value="Y">是</Radio>
                <Radio value="N">否</Radio>
            </RadioGroup>
        )
        //文章排序
        const sortField = form.getFieldDecorator('sort',{
            initialValue: article.get('sort') || 999,
            rules:[
                {type:"number",requied:true,message:"请输入文章排序"},
            ]
        })(
            <InputNumber placeholder="" style={inputStyle} min={1} max={999} />
        )
        //是否发布
        const publishField = form.getFieldDecorator('publish',{
            initialValue: article.get("publish") || 'Y'
        })(
            <RadioGroup>
                <Radio value="Y">是</Radio>
                <Radio value="N">否</Radio>
            </RadioGroup>
        )
    
        return (
            <Modal
                title={title}
                visible={visible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                width="800px"
            >
                <Form>
                    <div className="add-article-dialog">
                        <div className="block-fff">
                            <div className="title">
                                基础信息
                            </div>
                            <div>
                                <Row>
                                    <Col span={14}>
                                        {hiddenId}
                                        <FormItem
                                            label="文章标题"
                                            {...formItemLayout}
                                            required
                                        >
                                            {nameField}
                                        </FormItem>

                                        <FormItem
                                            label="文章栏目"
                                            {...formItemLayout}
                                            required
                                        >
                                           {sectionField}
                                            {this.renderSectionLink()}
                                        </FormItem>

                                        <FormItem
                                            label="作者"
                                            {...formItemLayout}
                                        >
                                            {authorField}
                                        </FormItem>
                                        <FormItem
                                            label="是否专题"
                                            {...formItemLayout}
                                        >
                                            {uniqueField}
                                        </FormItem>
                                    </Col>
                                    <Col span={10}>
                                        <FormItem
                                            label="排序"
                                            {...formItemLayout}
                                        >
                                            {sortField}
                                        </FormItem>
                                        <FormItem
                                            label="是否发布"
                                            {...formItemLayout}
                                        >
                                            {publishField}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </div>
                        </div>
                        <div className="block-fff">
                            <div className="title">
                                文章内容
                            </div>
                            <div>
                                <QMUeditor ready={this.saveEditorId} content={article.get('content') || ''} onChange={this.handleChange} />
                            </div>
                        </div>
                    </div>
                </Form>
            </Modal>
            
        );
    }
    renderSectionLink(){
        let link = (
            <span className="ant-form-text">
                <Link to="/article-section">管理文章栏目</Link>
            </span>
        )
        if(location.hash){
            if(location.hash.indexOf('article-section') !== -1){
                return null;
            }else{
                return link
            }
        }else{
            if(location.href.indexOf('article-section') !== -1){
                return null;
            }else{
                return link
            }
        }
    }

    saveEditorId = (editor) =>{
        // if(window.UM && eventId){
        //     this.editor = window.UM.getEditor(eventId) || null;
        // }
        this.editor = editor;
    }

    handleChange = (content) => {
        this.setState(()=>{
            return {
                content
            }
        })
    }
    /**
     * 确定按钮回调
     */
    handleOk = () => {
        const { onOk, form} = this.props;
        //验证输入值
        form.validateFields((err,fieldsValue)=>{
            if(err){
                return;
            }
            
            onOk({...fieldsValue,content:this.state.content})
        })
    }
    /**
     * 取消按钮回调
     */
    handleCancel = () => {
        const { onCancel, form } = this.props;
        
        onCancel();
        //重置初始值
        //form.resetFields();
        
    }
}

const FormArticleDialog = Form.create()(ArticleDialog)

export default FormArticleDialog;